<?php

namespace app\controllers;

class ApiController extends \Phalcon\Mvc\Controller
{
    public function getWeatherAction()
    {
        $ip = $this->request->getClientAddress(true);
        $address = \IP::find($ip);
        if (isset($address[3]) && !empty($address[3])) {
            $city = $address[3];
        } else if (isset($address[2]) && !empty($address[2])) {
            $city = $address[2];
        } else {
            $city = '北京';
        }
//        $queryUrl = 'http://wthrcdn.etouch.cn/weather_mini?city=' . $city;
        $queryUrl = 'http://wthrcdn.etouch.cn/WeatherApi?city=' . $city;
//        $content = \Curl::get($queryUrl, [
//            'Accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
//            'Accept-Encoding:gzip, deflate',
//            'Accept-Language:zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3',
//            'Cache-Control:max-age=0',
//            'User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64; rv:50.0) Gecko/20100101 Firefox/50.0'
//        ]);
        $content = file_get_contents($queryUrl);
        //拿到的数据是经过gzip压缩过的
        $content = gzdecode($content);
        //到手的数据是xml格式的
        $json = simplexml_load_string($content, 'SimpleXmlElement');
        $result = ['ip' => $ip, 'weather' => $json];
        return $this->response->setJsonContent($result);
    }
}